$(function(){
	$.pollCache = [];
	$.latestPollId = '';
	
	$('#page-poll-list').live('pageinit', function(event){
		geoInit();
		$(this).find('#search').keyup(Search);
	});
	
	var lat, lng;
	function success(position){					// get available polls at current location by using ajax.
		lat = position.coords.latitude;
		lng = position.coords.longitude;
		$.ajax({
	  		type: "post",
	  		url: CI_ROOT + "ajax/get_default_polls/" + $.latestPollId,
	  		data: {
	  			lat : position.coords.latitude,
	  			lng : position.coords.longitude
	  		},
	  		success : function(res){
	  			if(res.status && res.status == 'ok'){
	  				if( ! res.data)
	  					res.data = [];
	  					
	  				$.pollCache = res.data.concat($.pollCache);
	  				for(var i = 0; i < $.pollCache.length; i++)
	  					show_available_poll($.pollCache[i]);
	  			
	  				if($.pollCache.length > 0)
		  				$.latestPollId = $.pollCache[0].id;
		  			$.mobile.fixedToolbars.show(true);
	  			}else if (res.message){
	  				$.showNotification(res.message);
	  			}else{
	  				$.showNotification('서버와 통신 중 문제가 발생했습니다.');
	  			}
	  			
	  		},
	  		error : function(res){
	  			alert("an error occured");
	  		}
		});
	};
	
	function geoInit(){
		if (navigator.geolocation) {
	  		navigator.geolocation.getCurrentPosition(success);
		} else {
	  		$.showNotification("위치정보를 사용할 수 없습니다.");
		}
	}
		
	
	function show_available_poll(poll)					// print out available polls
	{
		var opt = {
			id : poll.id,
			midShow : poll.mid_show
		}
		
		$("#list-poll-template").clone()
			.removeAttr('id')
			.attr('id', 'list-poll-'+opt.id)
			.data('opt', opt)
			.click(vote_option)
			.find('.poll-head').attr('href', "#").end()
			.find('.poll-title').text(poll.title).end()
			.find('.poll-keyword').text(poll.keyword).end()
			.find('.poll_start').text(poll.poll_start).end()
			.find('.poll_end').text(poll.poll_end).end()
			.find('.ui-li-aside').text(CATEGORY_LIST[poll.category]).end()
			.insertAfter('.list-poll:last')
			.show();
	}
	
	// by using ajax, get a user status, and decide the click event : vote / login / mid-result show
	function vote_option()
	{
		var $this = $(this);
		var opt = $this.data('opt');
		var poll_id = opt.id;
		var mid_show = opt.midShow;
		$.ajax({													// ajax				
	  		type: "post",
	  		url: CI_ROOT + "ajax/can_user_vote",
	  		data: {
	  			poll_id : poll_id,
	  			lat : lat,
	  			lng : lng	  			
	  		},
	  		success : function(res){
	  			if(res.status == 'ok'){
	  				if(mid_show == 1){
	  					$.mobile.activePage.simpledialog({			// simple dialog is popped up to select vote or mid-result show
									'mode' : 'blank',
									'prompt': false,
									'forceInput': false,
									'cleanOnClose': true,
									'useModal': true,
									'fullHTML' : 
										"<a rel='close' data-role='button' href=" + CI_ROOT + "poll/vote/" + poll_id 
										+ " id='simpleclose'>설문하기</a> <a rel='close' data-role='button' href=" + CI_ROOT + "poll/result_question/" +  poll_id
										 + " id='simpleclose'>중간결과보기</a>"
						});
	  				} else $.mobile.changePage( CI_ROOT + "poll/vote/"+poll_id, { transition: "slideup"} );
	  			}else if(res.message){
	  				$.mobile.showNotification(res.message);			// error message is printed out if user is not allowed to vote
	  			}
	  		},
	  		error : function(res){
	  			alert("an error occured");
	  		}
		});
	}
	
	jQuery.expr[':'].containsCaseInsensitive = function(a, i, m) {
  			return jQuery(a).text().indexOf(m[3]) >= 0;
	};
	function Search() {
    	var SearchTerm = $(this).val();
    
       	if(SearchTerm){
       	// Find items to hide
		    var ItemsToHide = $("li", "#poll-list").not(":contains("+ SearchTerm  +")");
    		$(ItemsToHide).hide();
    
    	// Find items to show
		    var ItemsToShow = $(".poll-keyword:contains(" + SearchTerm + ")", "#poll-list").parent().parent().parent().parent();
	    	$(ItemsToShow).show();
	    }
    	else{
    		$("li", "#poll-list").not("#list-poll-template").show();
    	}
    	$.mobile.fixedToolbars.show(true);	
	}

});